package com.sportschain.app.core.network;

import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.convert.Converter;

import org.json.JSONObject;

import okhttp3.Response;

public abstract class JsonObjectCallback extends AbsCallback<JSONObject> {

    private JSONObjectConvert convert;

    public JsonObjectCallback() {
        this.convert = new JSONObjectConvert();
    }

    @Override
    public JSONObject convertResponse(Response response) throws Throwable {

        JSONObject jsonObject = convert.convertResponse(response);
        response.close();
        return jsonObject;
    }

    class JSONObjectConvert implements Converter<JSONObject> {

        @Override
        public JSONObject convertResponse(Response response) throws Throwable {
            if (response.body() == null) {
                throw new EmptyDataException("response.body() == null");
            }

            JSONObject jsonObject = new JSONObject(response.body().string());

            // 获取statusCode
            int statusCode;
            try {
                statusCode = jsonObject.getInt("status");
            } catch (Exception e) {
                statusCode = 100;
            }
            if (statusCode != 200) {
                throw new IllegalStateException(String.valueOf(statusCode));
            }

            LogUtils.d("json", jsonObject.toString());
            String dataStr = jsonObject.optString("data");
            if (!TextUtils.isEmpty(dataStr)) {
                return new JSONObject(dataStr);
            } else {
                throw new EmptyDataException("dataStr is empty");
            }
        }
    }
}
